package com.back.utils;

import com.back.model.dto.MailArgument;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Component
@Slf4j
public class SendMail {

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Autowired
    private Configuration configuration;

    /**
     * 检测邮件信息类
     * @param to
     * @param subject
     * @param text
     */


    /**
     * 发送纯文本邮件 不携带附件
     */

    public void sendTextMailMessage(MailArgument mailArgument) {
        checkMail(mailArgument);
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer, mailArgument.getName());
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(mailArgument.getTo().split(","));
            //邮件主题
            mimeMessageHelper.setSubject(mailArgument.getSubject());
            //邮件内容
            mimeMessageHelper.setText(mailArgument.getText(), true);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功：" + sendMailer + "->" + mailArgument.getTo());
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败：" + e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送纯文本邮件 携带附件
     */
    public void sendStaticEmail(MailArgument mailArgument, MultipartFile multipartFile) {
        checkMail(mailArgument);
        try {
            MimeMessageHelper helper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //谁发
            helper.setFrom(sendMailer);
            //谁接收
            helper.setTo(mailArgument.getTo());
            //邮件主题
            helper.setSubject(mailArgument.getSubject());
            //邮件内容   true 表示带有附件或html
            //邮件内容拼接
            helper.setText(mailArgument.getText(), true);
            //蒋 multpartfile 转为file
            File multipartFileToFile = MultipartFileToFile(multipartFile);
            FileSystemResource res = new FileSystemResource(multipartFileToFile);
            //添加内联资源，一个id对应一个资源，最终通过id来找到该资源
            helper.addAttachment(multipartFileToFile.getName(), res);
            javaMailSender.send(helper.getMimeMessage());
            System.out.println("发送邮件成功：" + sendMailer + "->" + mailArgument.getTo());
        } catch (MessagingException e) {
            System.out.println("发送邮件失败：" + e.getMessage());
        }
    }


    /**
     *
     * @param name
     * @return
     */
    public String creteTemlate(String name,String code) {
        List<Map<String, String>> rows = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        Template template = null;
        String s = "";
        try {
            template = configuration.getTemplate(name);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            s = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
        return s;
    }


    private File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码
        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void checkMail(MailArgument mailArgument) {
        if (StringUtils.isEmpty(mailArgument.getTo())) {
            throw new RuntimeException("邮件收信人不能为空");
        }
        if (StringUtils.isEmpty(mailArgument.getSubject())) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(mailArgument.getText())) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }
}
